/* 交易所页面，和银行基本一致的代码
 * @Author: Joursion
 * @Date: 2018-09-03 14:09:37
 * @Last Modified by: Joursion
 * @Last Modified time: 2018-09-03 17:44:16
 */

import React, { Component } from 'react';
import {
    View, Text, ScrollView, Image, ImageBackground,
    RefreshControl, Modal, TextInput, TouchableOpacity, Alert,
} from 'react-native';
import Redux, { connect } from 'react-redux';
import Toast from 'react-native-easy-toast';
import CInput from 'react-native-controlled-input';

import { TABBAR_LABEL, ROUTERMAP, Global, AVALIABLE_COIN_TYPES, API_MAP, TOAST_MESSAGE } from '../util/constants';
import BalanceItem from '../components/BalanceItem';
import { scaleSize, scaleFontSize } from '../util/size';
import icons from '../util/icons';
import * as balanceAction from '../actions/balance';
import * as exchangeBalanceAction from '../actions/exchangeBalance';
import { IReduxUserInfo, IReduxMarketInfo, IReduxBalanceInfo } from '../interface';
import { utilTotalBalanceAmountToBTC } from '../util/balanceUtil';
import { utilGetAmountToByCoinType } from '../util/marketUtil';
import { request } from '../util';
import NccButton from '../components/Button';
import { utilTransferInputValue } from '../util/util';

interface IProps {
    balance: IReduxBalanceInfo,
    navigation: any,
    updateBalanceInfo: Redux.Action,
    user: IReduxUserInfo,
    market: IReduxMarketInfo
}

interface IState {
    refreshing: boolean,
    lastRefreshTime: number,
    modalVisible: boolean,
    coinTypeToBank: string,
    exchangeToBankAmount: string,
    exchangeToBankCoinType: string,
    exchangeToBankButtonState: string,
}

const EXCHANGE_TO_EXCHANGE_BUTTON_STATE = {
    loading: '转账中...',
    onready: '确定',
}

const REFRESH_MS = 10000; // 刷新间隔

class ExchangeBalance extends Component<IProps, IState> {
    constructor(props) {
        super(props);
        this.state = {
            refreshing: false,
            lastRefreshTime: Date.now() - REFRESH_MS,
            modalVisible: false,
            coinTypeToBank: '',
            exchangeToBankAmount: '',
            exchangeToBankCoinType: '',
            exchangeToBankButtonState: EXCHANGE_TO_EXCHANGE_BUTTON_STATE.onready,
        }
    }

    static navigationOptions = {
        tabBarLabel: TABBAR_LABEL.balance,
        tabBarIcon: ({ focused }) => {
            if (focused) {
                return (
                    <Image source={icons.tabBalanceO} style={Global.tabIconStyles} />
                );
            }
            return (
                <Image source={icons.tabBalance} style={Global.tabIconStyles} />
            );
        },
    };

    componentWillUnmount() {
        this.resetExchangeToBankState();
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    }
    
    toast = (content: string) => {
        this.refs.toast.show(content);
    }

    reloadUserBalanceData = () => {
        request(API_MAP.balance, {
            method: 'post',
            data: { bankName: 'exchange1' }
        }, false, (err, res) => {
            if (err) {
                return null;
            }
            if (res && res.data) {
                try {
                    this.props.updateBalanceInfo(res.data);
                } catch (e) {
                    this.toast(TOAST_MESSAGE.SYSTEM_ERROR)
                }
            }
        })
    }

    onRefresh = () => {
        // return
        console.log('onrefresh', this.state.lastRefreshTime, Date.now());
        if (this.state.lastRefreshTime + REFRESH_MS > Date.now()) {
            this.toast(TOAST_MESSAGE.REFRESH_TO_MANY_TIMES);
            return;
        }
        this.setState({ refreshing: true, lastRefreshTime: Date.now() })
        request(API_MAP.balance, {
            method: 'POST',
            data: {
                bankName: 'exchange1'
            }
        }, false, (err, res) => {
            console.log('onRefresh ,res ...', res);
            this.setState({ refreshing: false });
            if (res.retCode == '00') {
                this.props.updateBalanceInfo(res.data);
                this.toast(TOAST_MESSAGE.REFRESH_FINISHED);
            }
        })
    }

    resetExchangeToBankState = () => {
        this.setState({ exchangeToBankAmount: '', exchangeToBankCoinType: '', modalVisible: false, exchangeToBankButtonState: EXCHANGE_TO_EXCHANGE_BUTTON_STATE.onready });
    }

    onChangeExchangeToBankAmount = (value) => {
        value = utilTransferInputValue(value, 'amount');
        this.setState({ exchangeToBankAmount: value });
        return value;
    }

    handleExchangeToBank = () => {

        const { exchangeToBankAmount, exchangeToBankCoinType, exchangeToBankButtonState } = this.state;

        console.log('handleExchangeToBank....', exchangeToBankAmount, exchangeToBankCoinType, exchangeToBankButtonState);

        if (exchangeToBankButtonState == EXCHANGE_TO_EXCHANGE_BUTTON_STATE.loading) {
            return;
        }

        const { balance } = this.props;


        if (!exchangeToBankAmount) {
            return Alert.alert(TOAST_MESSAGE.INVALID_AMOUNT);
        }

        if (!balance[exchangeToBankCoinType] || Number(exchangeToBankAmount) > balance[exchangeToBankCoinType]) {
            return Alert.alert(TOAST_MESSAGE.BALANCE_NOT_ENOUGH);
        }

        this.setState({ exchangeToBankButtonState: EXCHANGE_TO_EXCHANGE_BUTTON_STATE.loading });

        request(API_MAP.exchangeToBank, {
            method: 'POST',
            data: {
                amount: Number(exchangeToBankAmount),
                coinType: exchangeToBankCoinType,
            }
        }, false, (err, res) => {
            console.log('handleBankExchange...', res);
            if (res.retCode == '00') {
                this.reloadUserBalanceData();
                this.toast(TOAST_MESSAGE.SUCCESS);
            } else {
                this.toast(TOAST_MESSAGE.AGAIN_LATER);
            }
            this.resetExchangeToBankState();
            this.setState({ exchangeToBankButtonState: EXCHANGE_TO_EXCHANGE_BUTTON_STATE.onready });
        })
    }

    confirmExchangeToBank = (coinType: string) => {
        const { user } = this.props;
        console.log('user...', user);
        if (user && user.name) {
            this.setState({ modalVisible: true, exchangeToBankCoinType: coinType });
        } else {
            this.turnToPage(ROUTERMAP.login, { delUser: true });
        }
    }


    renderData = () => {
        let balanceInfo = this.props.balance;
        let market = this.props.market;
        let coinTypes = AVALIABLE_COIN_TYPES;
        let coinData: any = [];

        Object.keys(coinTypes).forEach((v, index) => {
            let type = coinTypes[v];
            let locked = balanceInfo[`${type}Locked`] || 0;
            let available = balanceInfo[`${type}`] || 0;
            let amountTo = utilGetAmountToByCoinType(market, type);
            amountTo = Number((available * amountTo).toFixed(4));
            coinData.push({
                type,
                available,
                locked,
                amountTo
            });
        })

        return (
            <View style={{
                display: 'flex',
                alignItems: 'center',
                marginTop: - scaleSize(24),
            }}>
                <View>
                    {
                        coinData.map((d, index) => {
                            return (
                                <BalanceItem {...d} key={`one-${index}`} topRightText={'转到银行'} topRightTextOnPress={() => {
                                    this.confirmExchangeToBank(d.type);
                                }} />
                            )
                        })
                    }
                </View>
            </View>
        )
    }

    render() {
        let { market, balance } = this.props;
        let balanceAmountToBTC = utilTotalBalanceAmountToBTC(balance, market);
        let amountTo = utilGetAmountToByCoinType(market, 'BTC');
        amountTo = Number((amountTo * balanceAmountToBTC).toFixed(4));
        return (
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                <ScrollView refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={this.onRefresh}
                    />
                }>
                    <View style={{ height: scaleSize(250) }}>
                        <ImageBackground source={icons.backgroundBalanceIntfo} style={{ height: scaleSize(250) }} resizeMode='cover'>
                            <View style={{ marginTop: 93, marginLeft: scaleSize(36) }}>
                                <Text style={{
                                    fontFamily: 'PingFangSC-Medium',
                                    fontSize: scaleFontSize(16),
                                    color: '#FFFFFF',
                                    lineHeight: scaleSize(22),
                                }}>总资产折合(交易所) (BTC) </Text>

                                <Text style={{
                                    fontFamily: 'Helvetica-Bold',
                                    fontSize: scaleFontSize(36),
                                    color: '#FFFFFF',
                                    lineHeight: scaleSize(43),
                                    marginTop: scaleSize(5),
                                }}>
                                    {balanceAmountToBTC}
                                </Text>

                                <Text style={{
                                    opacity: 0.65,
                                    fontFamily: 'Helvetica',
                                    fontSize: scaleFontSize(16),
                                    color: '#FFFFFF',
                                    marginTop: scaleSize(9),
                                }}>
                                    ≈ {amountTo} CNY
                        </Text>
                            </View>
                        </ImageBackground>
                    </View>
                    {
                        this.renderData()
                    }


                    <Modal
                        visible={this.state.modalVisible}
                        animationType={'none'}
                        transparent={true}
                    >
                        <TouchableOpacity activeOpacity={1} style={{ flex: 1 }} onPress={() => {
                            this.resetExchangeToBankState();
                        }}>
                            <View style={{
                                display: 'flex',
                                flex: 1,
                                backgroundColor: 'rgba(0,0,0,0.5)'
                            }}>
                                <View style={{
                                    alignSelf: 'center',
                                    marginTop: scaleSize(180),
                                    height: 300,
                                    width: '100%',
                                    backgroundColor: 'white',
                                    justifyContent: 'center',
                                    padding: scaleSize(20),
                                }}>
                                    <Text>转到银行</Text>
                                    <View style={{
                                        display: 'flex',
                                        flexDirection: 'row',
                                        justifyContent: 'space-between',
                                        marginTop: scaleSize(17),
                                    }}>
                                        <CInput style={[
                                            {
                                                borderWidth: 1,
                                                width: scaleSize(260),
                                                height: scaleSize(40),
                                                borderColor: Global.grayColor,
                                                paddingLeft: scaleSize(5),
                                            }
                                        ]}
                                            keyboardType={'numeric'}
                                            underlineColorAndroid={'transparent'}
                                            onChangeText={this.onChangeExchangeToBankAmount}
                                            value={this.state.exchangeToBankAmount}
                                        ></CInput>
                                        <Text style={{
                                            lineHeight: scaleSize(40),
                                        }}>{this.state.exchangeToBankCoinType}</Text>
                                    </View>
                                    <View style={{
                                        marginTop: scaleSize(30),
                                    }}>
                                        <NccButton text={this.state.exchangeToBankButtonState} onPress={this.handleExchangeToBank} buttonStyle={{
                                            // width: scaleSize(200),
                                        }} />
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                    </Modal>
                </ScrollView>
                <Toast ref='toast' position={'center'} />
            </View>
        )
    }
}

export default connect(
    (state) => ({
        balance: state.exchangeBalance,
        user: state.user,
        market: state.market,
    }),
    (dispatch) => ({
        updateBalanceInfo: (data) => dispatch(exchangeBalanceAction.updateBalanceInfo(data)),
        updateBalanceInfoWithCoinType: (coinType, amount) => dispatch(exchangeBalanceAction.updateBalanceInfoWithCoinType(coinType, amount)),
    })
)(ExchangeBalance);

// xy32351993